package com.bocai.aspect;

import com.bocai.CacheKey;
import com.bocai.Constants;
import com.bocai.Response;
import com.bocai.ResponseCode;
import com.bocai.config.RedisAdapter;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class LoginCheckerAspect {
	private static Logger logger = LoggerFactory.getLogger(LoginCheckerAspect.class);

	@Autowired
	private RedisAdapter redisAdapter;

	@Pointcut("@annotation(com.bocai.aspect.LoginChecker)")
    public void LoginRequired() {}
	
	@Around("LoginRequired()")  
    public Response loginCheckBefordExceed(ProceedingJoinPoint joinPoint) throws Throwable {
		try {
			HttpServletRequest request = getRequest();

			String token = request.getHeader("token");
			if(StringUtils.isBlank(token)) {
				return new Response(ResponseCode.NOT_LOGIN.getValue(), "token不能为空");
			}

			if(!redisAdapter.exists(CacheKey.TOKEN_PREFIX + token)) {
				return new Response(ResponseCode.NOT_LOGIN.getValue(), "token失效，请重新登录");
			}

			redisAdapter.expire(CacheKey.TOKEN_PREFIX + token, Constants.TOKEN_EXPIRE);

			return (Response)joinPoint.proceed();
		} catch (Exception e) {
			logger.error("ERROR ========>", e);
			return new Response(ResponseCode.SERVER_ERROR.getValue(), e.getMessage());
		}
    }

     /** * 在切面中获取http请求 * @return */
    private HttpServletRequest getRequest() {   
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }
}